package com.wyl.home.video

import android.content.Intent
import android.graphics.Color
import android.view.View
import android.widget.ImageView

import android.widget.RadioGroup
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.jzvd.Jzvd
import cn.jzvd.JzvdStd
import com.alibaba.android.arouter.facade.annotation.Route
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.wuhenzhizao.titlebar.statusbar.StatusBarUtils
import com.wyl.base.*
import com.wyl.base.bean.RoleData
import com.wyl.base.bean.VideoData
import com.wyl.base.binding.banner.GlideImageLoad
import com.wyl.base.binding.loadImage
import com.wyl.base.binding.url
import com.wyl.base.share.ShareSimpleAdapter
import com.wyl.base.share.showShareUrlDialog
import com.wyl.easydialog.EasyDialog
import com.wyl.easydialog.ViewHolder
import com.wyl.easydialog.ViewListener
import com.wyl.home.R
import com.wyl.home.databinding.VideoDetailActivityBinding
import com.wyl.home.databinding.VideoDetailItemBinding
import com.wyl.home.databinding.VideoDetailItemHeaderBinding
import com.wyl.home.leaderboard.LeaderboardActivity
import com.wyl.home.leaderboard.RolelistActivity
import com.wyl.libbase.base.BindingActivity
import com.wyl.libbase.binding.recyclerview.RecyclerViewDivider
import com.wyl.libbase.extend.autoWired
import com.wyl.libbase.extend.openActivity
import com.wyl.libbase.extend.toast
import com.wyl.libbase.utils.CountDownUtils
import com.wyl.libbase.utils.KLog
import io.ditclear.bindingadapter.*
import kotlinx.android.synthetic.main.video_detail_activity.*
import org.koin.android.viewmodel.ext.android.viewModel

@Route(path = VideoDetailPage)
class VideoDetailActivity : BindingActivity<VideoDetailActivityBinding>(), ItemClickPresenter<Any>,
    ItemDecorator {
    private val videoId by lazy { autoWired("videoid", "") }
    private val noId by lazy { autoWired("noid", "") }
    private val new by lazy { autoWired("new", false) }

    override fun getLayoutId(): Int = R.layout.video_detail_activity

    private val viewModel: VideoDetailViewModel by viewModel()
    private val mAdapter by lazy {
        MultiTypeAdapter(
            this,
            viewModel.dataSource,
            object : MultiTypeAdapter.MultiViewTyper {
                override fun getViewType(item: Any): Int = when (item) {
                    is VideoDetailViewModel -> TYPE_HEADER
                    else -> TYPE_NORMAL
                }
            }).apply {
            addViewTypeToLayoutMap(TYPE_HEADER, R.layout.video_detail_item_header)
            addViewTypeToLayoutMap(TYPE_NORMAL, R.layout.video_detail_item)
            itemDecorator = this@VideoDetailActivity
            itemPresenter = this@VideoDetailActivity
        }
    }

    private val itemDecorator by lazy { RecyclerViewDivider(this, RecyclerViewDivider.VERTICAL) }

    override fun decorator(
        holder: BindingViewHolder<ViewDataBinding>,
        position: Int,
        viewType: Int
    ) {
        if (position == 0) {
            // 头布局
            val headerBinding = holder.binding as VideoDetailItemHeaderBinding
            headerBinding.rvRole.apply {
                layoutManager = GridLayoutManager(context, 4)
                removeItemDecoration(itemDecorator)
                addItemDecoration(itemDecorator)
                adapter = SingleTypeAdapter(
                    context,
                    R.layout.video_detail_item_role,
                    viewModel.roleData
                ).apply {
                    itemPresenter = object : ItemClickPresenter<RoleData> {
                        override fun onItemClick(v: View, item: RoleData) {
                            showRoleDialog(item.id)
                        }
                    }
                }
            }
            headerBinding.rvNo.apply {
                layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                adapter = SingleTypeAdapter(
                    context,
                    R.layout.video_detail_item_card,
                    viewModel.videoNoData
                ).apply {
                    itemPresenter = object : ItemClickPresenter<VideoData> {
                        override fun onItemClick(v: View, item: VideoData) {
                            viewModel.videoNoData.forEach { it.playing = false }
                            item.playing = true
                            viewModel.videoPlayer.value = item
                        }
                    }
                }
            }
        } else {
            val binding = holder.binding as VideoDetailItemBinding

            if (binding.item?.type == "1") {
                binding.tvDetail.text = "更多抖音详情"
                binding.tvContent.visibility = View.GONE
                binding.video.apply {
                    binding.layoutVideo.visibility = View.VISIBLE
                    setUp(binding.item?.video?.url(), "")
                    binding.item?.cover?.url()?.let { thumbImageView.loadImage(it, 0) }
//                    startVideo()
                }
                binding.tvDetail.setOnClickListener {
                    JzvdStd.startFullscreenDirectly(
                        this,
                        JzvdStd::class.java,
                        binding.item?.video?.url(),
                        ""
                    )
                }
            } else {
                binding.tvDetail.text = "更多微博详情"
                binding.layoutVideo.visibility = View.GONE
                binding.tvContent.visibility = View.VISIBLE
                binding.tvDetail.setOnClickListener {
                    binding.item?.url?.let { openWebPage(it, "微博详情") }
                }
            }
        }
    }

    override fun onItemClick(v: View, item: Any) {
        when (v.id) {
            R.id.iv_shang -> showVideoDialog()
            R.id.tv_rolelist -> openActivity(RolelistActivity::class.java) {
                putExtra("data", viewModel.videoData.value?.appFolkOperaId)
            }
            R.id.iv_introduction -> {
                binding.layoutIntroduction.root.visibility = View.VISIBLE
                viewModel.videoData.value?.apply {
                    binding.layoutIntroduction.banner
                        .setImages(getIntroductionPicList(introductionpicture))
                        .setImageLoader(GlideImageLoad())
                        .start()
                }
            }
            else -> {
            }
        }
    }


    override fun onClick(v: View) {
        when (v.id) {
            R.id.back -> onBackPressed()
            R.id.share -> {
                showShareUrlDialog(
                    "http//:www.baidu.com",
                    "${userData?.name}邀请您使用短视频, 快快加入吧",
                    UMImage(this, R.drawable.logo),
                    "",
                    object : ShareSimpleAdapter() {
                        override fun onError(share_media: SHARE_MEDIA, t: Throwable) {
                            super.onError(share_media, t)
                            toast("分享失败")
                        }
                    })
            }
            R.id.tv_leaderboard -> openActivity(LeaderboardActivity::class.java) {
                putExtra("data", viewModel.videoData.value?.appFolkOperaId)
            }
            R.id.iv_mine -> openActivity(MinePage)
            R.id.iv_history -> openActivity(VideoHistoryPage)
            R.id.iv_message -> openActivity(MessagePage)
            R.id.iv_close_dialog_intro -> binding.layoutIntroduction.root.visibility = View.GONE
            else -> {
            }
        }
    }
    
    override fun initView() {
        StatusBarUtils.setStatusBarColor(window, Color.BLACK, 0)

        binding.vm = viewModel

        binding.recyclerview.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = mAdapter
        }
    }

    override fun loadData() {
        viewModel.videoPlayer.observe(this, Observer {
            KLog.d("videourl = ${it.appUrl}")
            KLog.d("currentTime = ${it.currentTime}")
            binding.video.apply {
                setUp(it.videourl, "")
                thumbImageView.loadImage(it.appUrl.url(), 0)
                seekToInAdvance = it.currentTime.toLong() * 1000
                startVideo()
                setOnCompleteListener {
                    viewModel.videoNoData.forEach { data -> data.playing = false }
                    val index = viewModel.videoNoData.indexOf(it)
                    val videoData = viewModel.videoNoData[index + 1]
                    videoData.playing = true
                    viewModel.videoPlayer.value = videoData
                }
            }
            viewModel.loadRoleSpeakData(it.appVideoId)
        })

        viewModel.shangSuccess.observe(this, Observer {
            showSuccessDialog()
        })

        viewModel.toast.observe(this, Observer {
            toast(it)
        })

        viewModel.error.observe(this, Observer {
            if (it == "金币不足") {
                showErrorDialog()
            } else {
                toast(it)
            }
        })

        viewModel.loading.observe(this, Observer {
            if (it) showLoadingDialog() else dissmissLoadingDialog()
        })

        viewModel.loadDetail(videoId, noId, new)
        viewModel.loadTiantong()

        viewModel.videoData.observe(this, Observer { video ->
            ad.setOnClickListener { openWebPage(video.url, "详情页") }
            ad_delete.setOnClickListener { ad_layout.visibility = View.GONE }
            CountDownUtils.delay(video.second.toInt()) {
                ad_layout.visibility = View.GONE
            }
        })
    }

    private fun showVideoDialog() {
        EasyDialog.Builder()
            .setLayoutId(R.layout.video_detail_shang_dialog)
            .setViewLisenter(object : ViewListener() {
                override fun convert(helper: ViewHolder, dialog: EasyDialog) {
                    helper.apply {
                        getView<ImageView>(R.id.image).setImageResource(R.drawable.detail_tiantong)
                        setText(
                            R.id.text,
                            "确定要赠送${viewModel.tiantongList[0]}支甜筒支持本剧集?"
                        )
                        setText(R.id.home_radiobutton, viewModel.tiantongList[0].toString())
                        setText(R.id.home_radiobutton2, viewModel.tiantongList[1].toString())
                        setText(R.id.home_radiobutton3, viewModel.tiantongList[2].toString())
                        setText(R.id.home_radiobutton4, viewModel.tiantongList[3].toString())
                        setOnClickListener(R.id.iv_close, View.OnClickListener {
                            dialog.dismiss()
                        })
                        setOnClickListener(R.id.tv_ok, View.OnClickListener {
                            dialog.dismiss()
                            val index =
                                when (helper.getView<RadioGroup>(R.id.home_radiogroup).checkedRadioButtonId) {
                                    R.id.home_radiobutton -> 0
                                    R.id.home_radiobutton2 -> 1
                                    R.id.home_radiobutton3 -> 2
                                    R.id.home_radiobutton4 -> 3
                                    else -> 0
                                }
                            viewModel.shangVideo(viewModel.tiantongList[index])
                        })
                        helper.getView<RadioGroup>(R.id.home_radiogroup)
                            .setOnCheckedChangeListener { _, id ->
                                val index =
                                    when (helper.getView<RadioGroup>(R.id.home_radiogroup).checkedRadioButtonId) {
                                        R.id.home_radiobutton -> 0
                                        R.id.home_radiobutton2 -> 1
                                        R.id.home_radiobutton3 -> 2
                                        R.id.home_radiobutton4 -> 3
                                        else -> 0
                                    }
                                helper.setText(
                                    R.id.text,
                                    "确定要赠送${viewModel.tiantongList[index]}支甜筒支持本剧集?"
                                )
                            }
                    }
                }
            })
            .setMargin(16)
            .setOutCancelable(false)
            .show(supportFragmentManager)
    }

    private fun showRoleDialog(id: String) {
        EasyDialog.Builder()
            .setLayoutId(R.layout.video_detail_shang_dialog)
            .setViewLisenter(object : ViewListener() {
                override fun convert(helper: ViewHolder, dialog: EasyDialog) {
                    helper.apply {
                        getView<ImageView>(R.id.image).setImageResource(R.drawable.detail_bangbangtang)
                        setText(
                            R.id.text,
                            """
                                是否赠送${viewModel.radio * viewModel.bbtList[0]}根棒棒糖支持该角色?
                                ${viewModel.bbtList[0]}支甜筒兑换${viewModel.radio * viewModel.bbtList[0]}根棒棒糖
                            """.trimIndent()
                        )
                        setText(
                            R.id.home_radiobutton,
                            (viewModel.bbtList[0] * viewModel.radio).toString()
                        )
                        setText(
                            R.id.home_radiobutton2,
                            (viewModel.bbtList[1] * viewModel.radio).toString()
                        )
                        setText(
                            R.id.home_radiobutton3,
                            (viewModel.bbtList[2] * viewModel.radio).toString()
                        )
                        setText(
                            R.id.home_radiobutton4,
                            (viewModel.bbtList[3] * viewModel.radio).toString()
                        )
                        setOnClickListener(R.id.iv_close, View.OnClickListener {
                            dialog.dismiss()
                        })
                        setOnClickListener(R.id.tv_ok, View.OnClickListener {
                            dialog.dismiss()
                            val index =
                                when (helper.getView<RadioGroup>(R.id.home_radiogroup).checkedRadioButtonId) {
                                    R.id.home_radiobutton -> 0
                                    R.id.home_radiobutton2 -> 1
                                    R.id.home_radiobutton3 -> 2
                                    R.id.home_radiobutton4 -> 3
                                    else -> 0
                                }
                            viewModel.shangRole(viewModel.bbtList[index], id)
                        })
                        helper.getView<RadioGroup>(R.id.home_radiogroup)
                            .setOnCheckedChangeListener { _, id ->
                                val index =
                                    when (helper.getView<RadioGroup>(R.id.home_radiogroup).checkedRadioButtonId) {
                                        R.id.home_radiobutton -> 0
                                        R.id.home_radiobutton2 -> 1
                                        R.id.home_radiobutton3 -> 2
                                        R.id.home_radiobutton4 -> 3
                                        else -> 0
                                    }
                                helper.setText(
                                    R.id.text,
                                    """
                                        是否赠送${viewModel.radio * viewModel.bbtList[index]}根棒棒糖支持该角色?
                                        ${viewModel.bbtList[index]}支甜筒兑换${viewModel.radio * viewModel.bbtList[index]}根棒棒糖
                                    """.trimIndent()
                                )
                            }
                    }
                }
            })
            .setMargin(16)
            .setOutCancelable(false)
            .show(supportFragmentManager)
    }

    private fun showErrorDialog() {
        EasyDialog.Builder()
            .setLayoutId(R.layout.video_detail_error_dialog)
            .setViewLisenter(object : ViewListener() {
                override fun convert(helper: ViewHolder, dialog: EasyDialog) {
                    helper.apply {
                        setOnClickListener(R.id.iv_close, View.OnClickListener {
                            dialog.dismiss()
                        })
                        setOnClickListener(R.id.tv_ok, View.OnClickListener {
                            dialog.dismiss()
                            // 去充值
                            openActivity(TiantongPage)
                        })
                    }
                }
            })
            .setMargin(16)
            .setOutCancelable(false)
            .show(supportFragmentManager)
    }

    private fun showSuccessDialog() {
        EasyDialog.Builder()
            .setLayoutId(R.layout.video_detail_success_dialog)
            .setViewLisenter(object : ViewListener() {
                override fun convert(helper: ViewHolder, dialog: EasyDialog) {
                    helper.apply {
                        setOnClickListener(R.id.tv_ok, View.OnClickListener {
                            dialog.dismiss()
                        })
                    }
                }
            })
            .setMargin(16)
            .setOutCancelable(false)
            .show(supportFragmentManager)
    }

    override fun onBackPressed() {
        if (Jzvd.backPress()) {
            return
        }
//        KLog.d("currentPositionWhenPlaying = $currentPositionWhenPlaying")
//        KLog.d("progress = ${progressBar.progress}")
        viewModel.addHistory(
            video.progressBar.progress,
            (video.currentPositionWhenPlaying / 1000).toInt()
        )
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
        Jzvd.releaseAllVideos()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //QQ与新浪不需要添加Activity，但需要在使用QQ分享或者授权的Activity中，添加：
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }
}
